#!/usr/bin/env bash
##  2018-03-26
## http://www.smallmi.com
##email: 1374409400@qq.com
##Seven Chou
##centos 6

case "$1" in
 install)
    installStatus=`netstat -pano | grep -e 22122 -e 23000 | grep LISTEN`
    libfastcommon_resp_code=`curl -I -m 10 -o /dev/null -s -w %{http_code} "http://192.168.201.53:8888/libfastcommon/V1.0.7.tar.gz"`
    fastdfs_resp_code=`curl -I -m 10 -o /dev/null -s -w %{http_code} "http://192.168.201.53:8888/FastDFS_v5.05.tar.gz"`

    if [ ! -n "$installStatus" ];then
        echo '开始下载libfastcommon，请稍等...'
        sleep 3

        if [ $libfastcommon_resp_code == 200 ];then
            wget http://192.168.201.53:8888/libfastcommon/V1.0.7.tar.gz
        else
            wget https://github.com/happyfish100/libfastcommon/archive/V1.0.7.tar.gz
        fi

        tar fxz V1.0.7.tar.gz && cd libfastcommon-1.0.7
        echo '开始编译安装...'
        sleep 3
        ./make.sh
        ./make.sh install

        cd ..

        echo '开始下载FastDFS_v5.05.tar.gz，请稍等...'
        sleep 3
        if [ $fastdfs_resp_code == 200 ];then
            wget http://192.168.201.53:8888/FastDFS_v5.05.tar.gz
        else
            wget https://nchc.dl.sourceforge.net/project/fastdfs/FastDFS%20Server%20Source%20Code/FastDFS%20Server%20with%20PHP%20Extension%20Source%20Code%20V5.05/FastDFS_v5.05.tar.gz
        fi

        tar fxz FastDFS_v5.05.tar.gz && cd FastDFS

        echo '开始编译安装...'
        sleep 3
        ./make.sh
        ./make.sh install

        echo '开始拷贝配置文件...'
        sleep 3
        sudo cp conf/* /etc/fdfs/

        echo '创建目录并配置tracker.conf文件...'
        sleep 3
        mkdir -p /ori-data/fastdfs/storage
        sed -i "s/\/home\/yuqing\/fastdfs/\/ori-data\/fastdfs/g" /etc/fdfs/tracker.conf
        sed -i "s/8080/80/g" /etc/fdfs/tracker.conf

        echo '启动tracker'
        sleep 3
        fdfs_trackerd /etc/fdfs/tracker.conf start

        echo '配置storage.conf文件...'
        sleep 3
        local_ip=`/sbin/ifconfig -a|grep inet|grep -v 127.0.0.1|grep -v inet6|awk '{print $2}'|tr -d "addr:"`
        sed -i "s/\/home\/yuqing\/fastdfs/\/ori-data\/fastdfs\/storage/g" /etc/fdfs/storage.conf
        sed -i "s/192.168.209.121/$local_ip/g" /etc/fdfs/storage.conf

        echo '启动storage'
        sleep 3
        fdfs_storaged /etc/fdfs/storage.conf start

        echo '清理安装文件...'
        sleep 3
        cd ..
        rm -fr FastDFS libfastcommon-1.0.7 FastDFS_v5.05.tar.gz V1.0.7.tar.gz

    else
        echo '端口被占用，请检查！'
    fi
 ;;

 stop)
    fdfs_trackerd /etc/fdfs/tracker.conf stop
    fdfs_storaged /etc/fdfs/storage.conf stop
 ;;

 start)
    fdfs_trackerd /etc/fdfs/tracker.conf start
    fdfs_storaged /etc/fdfs/storage.conf start
 ;;

 restart)
    fdfs_trackerd /etc/fdfs/tracker.conf restart
    fdfs_storaged /etc/fdfs/storage.conf restart
 ;;

 *)
 echo "Usage SuDo: {start|stop|restart|install}" >&2
 exit 3
 ;;
esac